<template>
  <div>
    <el-table
      v-if="columns.length"
      :data="pagedRows"
      border
      style="width: 100%">
      <el-table-column
        v-for="col in columns"
        :key="col.prop"
        :prop="col.prop"
        :label="col.label"
        min-width="100"
      />
    </el-table>

    <el-pagination
      v-if="columns.length"
      class="pagination"
      layout="prev, pager, next"
      :total="rows.length"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />

    <div v-else class="loading-text">
      Loading...
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watchEffect, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'

interface Column {
  prop: string
  label: string
}

const props = defineProps<{
  src: string
}>()

const rows = ref<any[]>([])
const columns = ref<Column[]>([])
const currentPage = ref(1)
const pageSize = 20

const pagedRows = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return rows.value.slice(start, start + pageSize)
})

function handlePageChange(page: number) {
  currentPage.value = page
}

async function loadData() {
  try {
    const res = await fetch(props.src)
    if (!res.ok) throw new Error(`Failed to fetch: ${res.status}`)
    const arrayBuffer = await res.arrayBuffer()
    const workbook = XLSX.read(arrayBuffer, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    const jsonData = XLSX.utils.sheet_to_json<any>(worksheet, { defval: '' })

    if (jsonData.length) {
      columns.value = Object.keys(jsonData[0]).map(key => ({ prop: key, label: key }))
      rows.value = jsonData
    } else {
      columns.value = []
      rows.value = []
    }
    currentPage.value = 1
  } catch (err: any) {
    ElMessage.error(err.message || '加载表格数据失败')
  }
}

watchEffect(() => {
  if (props.src) loadData()
})
</script>

<style scoped>
.loading-text {
  padding: 20px;
  text-align: center;
  color: #999;
}
.pagination {
  margin-top: 16px;
  text-align: center;
}
</style>
